import Timer from "./timer/timer"
import Graphics from "./graphics/graphics"
import Sensor from "./sensor/sensor"
import Touch from "./touch/touch"
import Media from "./media/media"
import Math from "./etc/math"
import Ui from "./ui/ui"
import Particle from "./etc/particle"
import Loader from "./etc/loader"
import System from "./system/system"
import State from "./etc/state"
export default class love{
  constructor(name = "unknown"){
    this.name = name
    this.timer = new Timer()
    this.graphics = new Graphics()
    this.sensor = new Sensor()
    this.touch = new Touch()
    this.media = new Media()
    this.math = new Math()
    this.loader = new Loader()
    this.system = new System()
    this.state = new State()
    this.ui = new Ui(this)
    this.particle = new Particle(this)
  }
  run(){
    //console.log("love load")
    this.touch.load(this)
    this.boundLoop = this.loop.bind(this)
    requestAnimationFrame(this.boundLoop)
  }
  loop(){
    //console.log("love loop")
    var dt = this.timer.step()
    this.touch.update(dt)
    this.particle.update(dt)
    this.update(dt)
    this.render()
    if (this.freezed) {
      return this.switch(this.freezed)
    }
    else {
      this.frameID = requestAnimationFrame(this.boundLoop)
    }
  }
  enter(){}
  update(dt){}
  render(){
    //console.log("love draw")
    this.graphics.origin()
    this.graphics.push()
    this.graphics.clear(this.graphics.getBackgroundColor())
    this.graphics.applyResolutionAdjust()
    this.draw()
    this.graphics.origin()
    this.graphics.applyResolutionAdjust()
    this.particle.draw()
    this.ui.draw()
    this.touch.draw()
    this.graphics.pop()
  }
  quit(){
    for (var i in this.media.buff){
      this.media.buff[i].stop()
    }
    this.touch.unload()
    this.ui.clear()
    this.graphics.clear("#000000")
    cancelAnimationFrame(this.frameID)
  }
  switch(name,data){
    if (this.freezed){return}
    this.freezed = name
    let newLove = this.state.buff[name]
    this.quit.bind(this)()
    newLove.freezed = false
    newLove.state.buff = this.state.buff
    newLove.loader.transfer(this.loader.data)
    newLove.enter.bind(newLove)(data)
    newLove.run.bind(newLove)()
  }
  start(){
    this.enter()
    this.run()
  }
  print = console.log
}
